package com.android.takegism.service;

import android.os.Message;
import android.util.Log;

import com.android.takegism.ui.BeforeUserMainActivity;
import com.android.takegism.ui.ChooseActivity;
import com.android.takegism.ui.UserMainActivity;
import com.android.takegism.utils.MyContext;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class ClientService {

    private MyContext myContext = MyContext.getInstance();
    private Socket client = null;
    private String ip;
    private int port;
    private boolean isConnected = false;
    private Thread thread;
    private ReadThread readThread;
    private InputStream inputStream = null;
    private OutputStream outputStream = null;
    private byte[] msgBuffer = null;

    private BufferedReader br = null;
    private BufferedWriter bw = null;

    public ClientService() {
        Object ipObj = myContext.getStatics("ip");
        Object portObj = myContext.getStatics("port");
        if (ipObj != null && portObj != null) {
            ip = ipObj.toString();
            port = Integer.parseInt(portObj.toString());
        }
        System.out.println(ip + "---" + port);
    }

    public Socket getClient() {
        return client;
    }

    /**
     * socket连接
     * 用户登录
     */
    public void doConnect() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //connect()步骤
                try {
                    System.out.println("进来了，连接SOCKET");
                    client = new Socket(ip, port);
                    System.out.println("开始连接socket：" + client);
//                    client.setSoTimeout(60000);
                    if (client.isConnected()) {
                        isConnected = true;

                        inputStream = client.getInputStream();
                        outputStream = client.getOutputStream();

                        br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                        bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                        sendMsg(client.getLocalSocketAddress().toString() + "@:\tHELLO!");
                        //读线程
                        readThread = new ReadThread();
                        readThread.start();
                        System.out.println("//读线程");
//                        //写线程
//                        System.out.println("//写线程");
                        //网络连接发送成功消息
                        ChooseActivity.mainHandler.sendEmptyMessage(0x5555);
                        System.out.println("网络连接成功");
                        System.out.println("=======发送handler指出连接成功=======");
//                        MyContext.getInstance().setStatics("clientService",this);
                    } else {
                        isConnected = false;
                        //网络连接失败,发送失败消息
                        ChooseActivity.mainHandler.sendEmptyMessage(0x5556);
                        System.out.println("//网络连接失败");
                        System.out.println("=======发送handler指出连接失败=======");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("-----new SocketError-----01");
                    System.out.println("=======发送handler指出连接失败=======");
                    ChooseActivity.mainHandler.sendEmptyMessage(0x5556);
                }
            }
        });
        thread.start();
    }


    /**
     * 读线程
     */
    public class ReadThread extends Thread {

        public void run() {

            // 方法一
//            byte[] buffer = new byte[1024*2];
//
//            while (isConnected && client != null && client.isConnected()) {
//                System.out.println(isConnected +"=>client"+ client+"isConnected:"+ client.isConnected());
//                try {
//                    int readSize = inputStream.read(buffer);
//                    System.out.println("readSize:" + readSize);
//                    if (readSize > 0) {
//                        String str = new String(buffer, 0, readSize, "UTF-8");                  //编码方式  解决收到数据乱码
//                        System.out.println("读线程str:" + str);
//                        //接收的数据
//                        Message msg = new Message();
//                        msg.what = 0x1111;
//                        msg.obj = str;
//                        ChooseActivity.mainHandler.sendMessage(msg);
//
//                        System.out.println("=======(未指明handler有谁处理！)发送handler指明信息/类型（有对应处理方法：打印输出、逻辑运算控制？）=======");
//                    }
//                    else {
//                        inputStream.close();
//                        Log.d("readError:", "close connect...");
//                        break;
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//          方法一end

            try {
                String str;
                System.out.println(isConnected + "=>client" + client + "isConnected:" + client.isConnected());
                while (isConnected && client != null && client.isConnected() && (str = br.readLine()) != null) {
                    System.out.println("读线程str:" + str);
//                        接收的数据

                    if (UserMainActivity.mainHandler != null && str.indexOf("#") == -1) {
                        Message msg = UserMainActivity.mainHandler.obtainMessage();
                        msg.what = 0x1111;
                        msg.obj = str;
                        UserMainActivity.mainHandler.sendMessage(msg);
                    }
                    if (BeforeUserMainActivity.mainHandler != null && str.indexOf("#") != -1) {
                        Message msg = BeforeUserMainActivity.mainHandler.obtainMessage();
                        msg.what = 0x1111;
                        msg.obj = str;
                        BeforeUserMainActivity.mainHandler.sendMessage(msg);
                    }

                    System.out.println("=======发送handler指明信息/类型（有对应处理方法：打印输出、逻辑运算控制？）=======");

                }
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    br.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                Log.d("readError:", "close connect...");
                if (UserMainActivity.mainHandler != null)
                    UserMainActivity.mainHandler.sendEmptyMessage(0x1113);
                if (BeforeUserMainActivity.mainHandler != null)
                    BeforeUserMainActivity.mainHandler.sendEmptyMessage(0x1113);
                ChooseActivity.mainHandler.sendEmptyMessage(0x5556);
            }
            try {
                if (client == null)
                    return;
                if (client.isConnected())
                    client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送消息
     */
    public void sendMsg(final String str) {
        if (client == null || client.isClosed()) {
            System.out.println("还没有连接上服务器！");
            return;
        }
        System.out.println(isConnected + "=>client" + client + "isConnected:" + client.isConnected() + "isClosed?:" + client.isClosed());
        new Thread(new Runnable() {
            @Override
            public void run() {

                if (client != null && client.isConnected()) {
//                    方法一
//                    try {
//                        msgBuffer = str.getBytes("UTF-8");
//                        outputStream = client.getOutputStream();
//                        outputStream.write(msgBuffer);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    System.out.println("发送数据：" + str);
//                    方法一end
                    try {
                        bw.write(str);
                        bw.newLine();
                        bw.flush();
                        System.out.println("发送数据：" + str);
                    } catch (IOException e) {
                        e.printStackTrace();
                        if (UserMainActivity.mainHandler != null)
                            UserMainActivity.mainHandler.sendEmptyMessage(0x1113);
                        if (BeforeUserMainActivity.mainHandler != null)
                            BeforeUserMainActivity.mainHandler.sendEmptyMessage(0x1113);
                        ChooseActivity.mainHandler.sendEmptyMessage(0x5556);
                    }
                } else {
                    isConnected = false;
                    try {
                        if (client != null) client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }


    /**
     * 判断连接状态
     */
    public boolean isConnected() {
        return client != null && !client.isClosed();
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        System.out.println("===================================================期望能断开连接");
        if (client == null || client.isClosed()) {
            System.out.println("早就断开了");
        } else {
            try {
                client.close();
            } catch (IOException e) {

            }
            client = null;
            isConnected = false;
            System.out.println("执行断开连接");
        }
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }


}
